package main

import (
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"math/big"
	"time"
)

func main() {
	//创建一个钱包文件
	curve1 := elliptic.P256()
	privateKey1, _ := ecdsa.GenerateKey(curve1, rand.Reader)

	privaKey := hex.EncodeToString(privateKey1.D.Bytes())                                                        //私钥
	publicKey := hex.EncodeToString(append(privateKey1.PublicKey.X.Bytes(), privateKey1.PublicKey.Y.Bytes()...)) //公钥

	fmt.Println("你的私钥：", privaKey)
	fmt.Println("你的公钥：", publicKey)
	data := []byte("今天吃饭了吗？")
	dataHash := sha256.Sum256(data)

	//签名此内容
	r, s, _ := ecdsa.Sign(rand.Reader, privateKey1, dataHash[:])

	fmt.Println("++++++++++++++++验证签名中")
	time.Sleep(time.Second * 2)

	var newD big.Int
	var newX big.Int
	var newY big.Int
	dd, _ := hex.DecodeString(privaKey)
	xy, _ := hex.DecodeString(publicKey)

	newD.SetBytes(dd)
	newX.SetBytes(xy[0 : len(xy)/2])
	newY.SetBytes(xy[len(xy)/2:])

	//另外一边生成一个新的圆
	curve2 := elliptic.P256()
	privateKey2 := ecdsa.PrivateKey{
		PublicKey: ecdsa.PublicKey{
			Curve: curve2,
			X:     &newX,
			Y:     &newY,
		},
		D: &newD,
	}

	//用公钥验证签名
	isok := ecdsa.Verify(&privateKey2.PublicKey, dataHash[:], r, s)
	fmt.Println("验证结果：", isok)
}
